const XLSX = require('xlsx');
const crypto = require('crypto');
const fs = require('fs');
const { marked } = require('marked');
const createDOMPurify = require('dompurify');
const { JSDOM } = require('jsdom');

// 创建DOMPurify实例
const window = new JSDOM('').window;
const DOMPurify = createDOMPurify(window);

/**
 * 解析Excel文件
 * @param {string} filePath - 文件路径
 * @returns {Object} - 包含headers和data的对象
 */
const parseExcelFile = (filePath) => {
    // 添加编码配置，支持中文字符
    const workbook = XLSX.readFile(filePath, {
        codepage: 65001, // UTF-8编码，支持中文字符
        cellText: false,
        cellDates: true
    });
    const sheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[sheetName];
    const jsonData = XLSX.utils.sheet_to_json(worksheet, { 
        header: 1, 
        defval: '',
        raw: false // 确保文本按字符串处理
    });
    
    if (jsonData.length === 0) return { headers: [], data: [] };
    
    const headers = jsonData[0];
    const data = jsonData.slice(1).map((row, index) => {
        const rowData = {};
        headers.forEach((header, colIndex) => {
            rowData[header] = row[colIndex] || '';
        });
        rowData._rowIndex = index;
        return rowData;
    });
    
    return { headers, data };
};

/**
 * 计算文件哈希
 * @param {string} filePath - 文件路径
 * @returns {string} - 文件MD5哈希值
 */
const calculateFileHash = (filePath) => {
    const fileBuffer = fs.readFileSync(filePath);
    const hashSum = crypto.createHash('md5');
    hashSum.update(fileBuffer);
    return hashSum.digest('hex');
};

/**
 * 渲染Markdown表格
 * @param {string} content - Markdown内容
 * @returns {string} - 渲染后的HTML内容
 */
const renderMarkdownTable = (content) => {
    if (!content || typeof content !== 'string') return content;
    
    // 检查是否包含Markdown表格
    const tableRegex = /\|.*\|/g;
    if (!tableRegex.test(content)) return content;
    
    try {
        const html = marked(content);
        return DOMPurify.sanitize(html);
    } catch (error) {
        console.error('Markdown渲染错误:', error);
        return content;
    }
};

module.exports = {
    parseExcelFile,
    calculateFileHash,
    renderMarkdownTable
};